package com.bear.hospital.service.minio.impl;

/**
 * @Author： zmwx
 * @Date： 2025/2/12 14:50
 * @Describe：
 */

import com.bear.hospital.config.MinioConfig;
import com.bear.hospital.service.minio.MinioService;
import io.minio.PutObjectArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
public class MinioServiceImpl implements MinioService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;
    @Value("${minio.url}")
    private String url;

    @Override
    public String uploadImage(String bucketName, MultipartFile file) {
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(file.getOriginalFilename())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()) // 设置正确的 MIME 类型以支持在线预览
                    .build();
            minioClient.putObject(args);
            return url + "/" + file.getOriginalFilename(); // 返回可访问的 URL
        } catch (Exception e) {
            log.error("图片上传失败:{}", e);
            throw new RuntimeException("图片上传失败", e);
        }
    }

    public void uploadFile(String bucketName, MultipartFile file) {
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(file.getOriginalFilename())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            minioClient.putObject(args);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败", e);
        }

    }
}
